<?php

namespace Duante\GuLu;

use Duante\GuLu\strings\StringsInterface;

class Strings implements StringsInterface
{
    /**
     * 生成指定长度随机字符串
     * @param int $length 字符串长度
     * @return bool|string
     */
    public static function random($length = 10)
    {
        $str = "QWERTYUIOPASDFGHJKLZXCVBNM1234567890qwertyuiopasdfghjklzxcvbnm";
        $s = substr(str_shuffle($str), mt_rand(0, strlen($str) - 11), $length);

        return $s;
    }

    /**
     * 检查字符串中是否包含某字符串
     * @param string $haystack 检测的字符串
     * @param string|array $needles
     * @return bool
     */
    public static function contains($haystack, $needles)
    {
        foreach ((array)$needles as $needle) {
            if ($needle != '' && mb_strpos($haystack, $needle) !== false) {
                return true;
            }
        }

        return false;
    }

    /**
     * 检查字符串是否以某些字符串开头
     * @param $haystack
     * @param $needles
     * @return bool
     */
    public static function beginWith($haystack, $needles)
    {
        foreach ((array)$needles as $needle) {
            if ($needle != '' && mb_strpos($haystack, $needle) === 0) {
                return true;
            }
        }

        return false;
    }

    /**
     * 检查字符串是否以某些字符串结尾
     * @param $haystack
     * @param $needles
     * @return bool
     */
    public static function endWith($haystack, $needles)
    {
        foreach ((array)$needles as $needle) {
            if ((string)$needle === static::getSub($haystack, -static::getLength($needle))) {
                return true;
            }
        }

        return false;
    }

    /**
     * 截取字符串
     * @param $string 字符串
     * @param $start 起始位置
     * @param null $length 截取长度
     * @return string
     */
    public static function getSub($string, $start, $length = null)
    {
        return mb_substr($string, $start, $length, 'UTF-8');
    }

    /**
     * 获取字符串长度
     * @param $value
     * @return int
     */
    public static function getLength($value)
    {
        return mb_strlen($value);
    }

    /**
     * 字符串转小写
     * @param $value
     * @return string
     */
    public static function toLower($value)
    {
        return mb_strtolower($value, 'UTF-8');
    }

    /**
     * 字符串转为大写
     * @param $value
     * @return string
     */
    public static function toUpper($value)
    {
        return mb_strtoupper($value, 'UTF-8');
    }
}